<template>
  <div class="common-list-view__v2">
    <div class="common-list-view-header__v2 a-center mb_12">
      <div class="common-list-view-header__v2-left">
        <el-dropdown v-if="btnAuth.createProjectAuth">
          <el-button type="primary" icon="el-icon-plus">{{ $t('common.base.create') }}</el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item v-for="(item, index) in projectTypeList" :key="index">
              <div @click="openProjectCreateTab(item.id)">{{ item.label }}</div>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <el-button type="plain-third" @click="deleteHandler" v-if="btnAuth.deleteProjectAuth"> <i class="iconfont icon-delete"></i>{{ $t('common.base.delete') }} </el-button>
      </div>
      <div class="common-list-view-header__v2-right">
        <!-- <el-dropdown>
          <span class="el-dropdown-link cur-point acenter">
            {{ $t('common.base.moreOperator') }}
            <i class="iconfont icon-fdn-select ml_4"></i>
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item>
              <div class="import-project">
                {{$t('common.base.import')}}
                <div class="import-project-item import-item">
                  <div v-for="(item, index) in projectTypeList" :key="index" @click="importHandler(item.id)">
                    {{ item.name }}
                  </div>
                </div>
              </div>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown> -->
        <div class="flex-x">
          <el-dropdown trigger="click">
            <div class="el-dropdown-link cur-point acenter">
              <span>{{ $t('common.base.moreOperator') }}</span>
              <i class="iconfont icon-fdn-select ml_4"></i>
            </div>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>
                <div @click="beforeExport(false, $refs.exportPanelDom)">{{ $t('projectManage.projectList.text1') }}</div>
              </el-dropdown-item>
              <el-dropdown-item>
                <div @click="beforeExport(true, $refs.exportPanelDom)">{{ $t('projectManage.projectList.text2') }}</div>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <div class="el-dropdown-link cur-point acenter mar-l-24" @click="handleSelectColumn">
            {{ $t('common.base.choiceCol') }}
            <i class="iconfont icon-fdn-select ml_4"></i>
          </div>
        </div>
      </div>
    </div>

    <el-table v-table-style v-if="columns.length" v-loading="loading" ref="tableComponentRef" header-row-class-name="common-list-table-header__v2" class="bbx-normal-list-box" :data="dataList" :height="tableContainerHeight" @select="handleSelection($event, dataList)" @select-all="handleSelection($event, dataList)" @header-dragend="handlerHeaderDragend" @sort-change="handlerSortChanged" stripe border>
      <el-table-column type="selection" width="48" align="center"></el-table-column>
      <template v-for="column in columns">
        <el-table-column v-if="column && column.show" :align="column.align" :key="column.field" :label="column.displayName" :prop="column.field" :width="column.width" :min-width="column.minWidth" :sortable="column.sortable" :fixed="column.fixLeft || false" show-overflow-tooltip>
          <template slot-scope="scope">
            <!-- start 编号 -->
            <template v-if="column.field === 'projectNo'">
              <div class="view-detail-btn" @click="openProjectViewTab(scope.row)">{{ scope.row.projectNo }}</div>
            </template>
            <!-- end 编号 -->

            <!-- 项目名称 S -->
            <template v-else-if="column.field === 'projectName'">
              <div class="align-items-center">
                <span>{{ scope.row.projectName }}</span>
                <ProjectTaskLabel class="ml_8" :current-row-data="scope.row"/>
              </div>
            </template>
            <!-- 项目名称 E -->

            <!-- start 状态 -->
            <template v-else-if="column.field === 'projectStatusName'">
              <span class="status" :style="{ 'background-color': scope.row.projectStatusColor }">{{ scope.row.translateText }}</span>
            </template>
            <!-- end 状态 -->

            <!-- start 项目进度 -->
            <template v-else-if="column.field === 'projectProcess'">
              <el-progress :percentage="scope.row.projectProcess"></el-progress>
            </template>
            <!-- end 项目进度 -->

            <!--  start 延期任务 -->
            <template v-else-if="column.field === 'delayedTasks'">
              <span>{{ renderDelayedTasks(scope.row) }}</span>
            </template>
            <!--  end 延期任务 -->

            <!-- 富文本 -->
            <template v-else-if="column.formType === 'richtext'">
              <div class='view-detail-btn' @click.stop="openRichtextVisible(scope.row, column)">
                <span v-if="scope.row.attributeMap && scope.row.attributeMap[column.field]">{{$t('common.base.view')}}</span>
              </div>
            </template>

            <template v-else>
              {{ $formatFormField(column, scope.row) }}
            </template>
          </template>
        </el-table-column>
      </template>

      <el-table-column fixed="right" :label="$t('common.base.operation')" width="100">
        <template slot-scope="scope">
          <el-button type="text" @click="openProjectViewTab(scope.row)">{{ $t('common.base.detail') }}</el-button>
        </template>
      </el-table-column>

      <template slot="empty">
        <BaseListForNoData v-show="!loading" :notice-msg="$t('common.base.tip.noData')"></BaseListForNoData>
      </template>
    </el-table>

    <!-- 分页 S -->
    <div class="table-footer bbx-normal-table-footer-10">
      <div class="list-info">
        <i18n path="common.base.table.totalCount">
          <span place="count" class="level-padding">{{ dataListPageInfo.total || 0 }}</span>
        </i18n>

        <template v-if="multipleSelection.length > 0">
          <i18n path="common.base.table.selectedNth">
            <span place="count" class="color-primary pad-l-5 pad-r-5">{{ multipleSelection.length }}</span>
          </i18n>
          <span class="color-primary pad-l-5 cur-point" @click="clearSelection">{{ $t('common.base.clear') }}</span>
        </template>
      </div>

      <el-pagination background @current-change="handlePageNumChange" @size-change="handleSizeChange" :page-sizes="defaultTableData.defaultPageSizes" :page-size="searchParams.pageSize" :current-page="searchParams.pageNum" layout="prev, pager, next, sizes, jumper" :total="dataListPageInfo.total"> </el-pagination>
    </div>
    <!-- 分页 E -->

    <!-- s 导入 -->
    <base-import ref="importModalRef" :title="$t('common.base.import')" :action="`/excels/paas/form/import?formTemplateId=${importTypeId}`" :template-url="`/api/paas/outside/pc/form/excel/import/template?formTemplateId=${importTypeId}`"></base-import>
    <!-- e 导入 -->

    <!-- 导出 -->
    <base-export-group ref="exportPanelDom" :alert="BbxExportAlert" :columns="BbxExportColumns" :build-params="BbxBuildExportParams" :group="true" :validate="() => null" :needchoose-break="false" method="post" :action="BbxExportHttpFnc" :is-show-export-tip="isOpenData" />
    <!--查看富文本 -->
    <base-view-rich-text ref="baseViewRichTextRef"></base-view-rich-text>
  </div>
</template>

<script>
/* model */
import { ViewTypeComponentNameEnum } from '@src/modules/projectManage/projectManageList/model';
import { DELETE_SUCCESS_MESSAGE, PLEASE_SELECT_DATA_MESSAGE } from '@src/model/const/Alert';
import StorageKeyEnum from '@model/enum/StorageKeyEnum';
/* util */
import Platform from '@src/util/platform';
import Log from '@src/util/log';
import { t } from '@src/locales';
import _, { cloneDeep } from 'lodash';
import { defaultTableData, useTabelExportNormalDataHook } from '@src/util/table';
import { renderDelayedTasks } from '@src/modules/projectManage/projectManageList/util/renderProjectTable.js'
/* hooks */
import { useTable } from '@src/modules/projectManage/projectManageList/hooks/useTable';
import { useOpenTab } from '@src/modules/projectManage/projectManageList/hooks/useOpenTab';
import { useFetchDeleteProject, useFetchProjectTableList } from '@src/modules/projectManage/projectManageList/hooks/useFetch';
/* vue */
import { ref, reactive, onMounted, watch, computed } from 'vue';
import { projectListExport } from '@src/api/Export';
import { getProjectExportFieldList } from '@src/api/ProjectManage';
import { projectServiceReportForExport } from '@src/modules/projectManage/common'

import ProjectTaskLabel from '@src/modules/projectManage/components/projectTaskLabel.vue'

export default {
  name: ViewTypeComponentNameEnum.Table,
  props: {
    columns: {
      type: Array,
      default: [],
    },
    params: {
      type: Object,
      default: {},
    },
    btnAuth: {
      type: Object,
      default: {},
    },
    projectTypeList: {
      type: Array,
      default: [],
    },
  },
  components: {
    ProjectTaskLabel
  },
  setup(props, { emit }) {
    const { tableComponentRef, multipleSelection, selectedIds, handleSelection, clearSelection, matchSelected, disposeHeaderDragendColumns, disposeTableSortChanged } = useTable();
    const { loading, dataList, dataListPageInfo, fetchProjectTableList } = useFetchProjectTableList();
    const { fetchDeleteProject } = useFetchDeleteProject();
    const { openProjectCreateTab, openProjectViewTab } = useOpenTab();
    // 导入组件ref
    const importModalRef = ref(null);
    // 导入类型id
    const importTypeId = ref('');
    const baseViewRichTextRef = ref(null);
    // 表格高度
    const tableContainerHeight = ref('calc(100% - 100px)');

    const { getField:getExportField } = projectServiceReportForExport()

    // 搜索参数
    const searchParams = reactive({
      pageSize: 10,
      pageNum: 1,
      column: '',
      asc: null,
    });
    /** 打开富文本弹窗 */
    const openRichtextVisible = (row, column)=> {
      const richtextId = row?.attributeMap?.[column.fieldName]  || ''
      baseViewRichTextRef.value.openDialog(richtextId)
    }

    // 选择列
    const handleSelectColumn = () => {
      emit('handleSelectColumn');
    };

    // 表头拖动列改变宽度
    const handlerHeaderDragend = (newWidth, oldWidth, column) => {
      disposeHeaderDragendColumns(newWidth, column, props.columns, ViewTypeComponentNameEnum.Table);
    };

    // 表格排序变化事件
    const handlerSortChanged = option => {
      const { column, asc } = disposeTableSortChanged(option);
      const info = {
        customer: 'customerId',
        createUser: 'createUid',
      };

      searchParams.column = info[column] || column;
      searchParams.asc = asc;

      search();
    };

    // 删除事件
    const deleteHandler = async () => {
      if (!selectedIds.value.length) return Platform.alert(PLEASE_SELECT_DATA_MESSAGE);

      try {
        // 获取删除提示
        const confirm = await Platform.confirm(t('common.base.tip.confirmDeleteTip'));
        if (!confirm) return;

        fetchDeleteProject(selectedIds.value).then(() => {
          Platform.alert(DELETE_SUCCESS_MESSAGE);
          clearSelection();

          // 延迟刷新
          setTimeout(() => {
            handlePageNumChange(1);
          }, 600);
        });
      } catch (error) {
        Log.error(error, deleteHandler.name);
      }
    };

    // 导入
    const importHandler = id => {
      importTypeId.value = id;
      importModalRef.value?.open();
    };

    // 搜索
    const search = isRefresh => {
      // 需要刷新
      if (isRefresh) return handlePageNumChange(1);

      const params = { ...searchParams, ...props.params };
      fetchProjectTableList(params);
    };

    // 页码跳转
    const handlePageNumChange = pageNum => {
      searchParams.pageNum = pageNum;
      dataList.value = [];
      search();
    };

    // 分页条数改变
    const handleSizeChange = pageSize => {
      searchParams.pageSize = pageSize;
      searchParams.pageNum = 1;
      search();
    };
    const BbxExportColumns = ref([]);
    const exportTemplateId = ref(null)
    const setBbxExportColumns = arr => {
      let arr_ = cloneDeep(arr);
      let arr1 = [];
      let arr2 = [];
      arr_.forEach(i => {
        if(i.formType === 'info' || i.formType === 'autograph' || i.formType === 'separator' || i.formType === 'attachment'){
          return
        }
        i['export'] = true;
        i['field'] = i.fieldName;
        i['label'] = i.displayName;
        if (i.isSystem === 1) {
          arr1.push(i);
        } else {
          arr2.push(i);
        }
      });
      const fieldsArr = {
        label: t('common.form.fieldGroupName.system'),
        value: 'projectExport',
        columns: arr1,
      };
      const attributeArr = {
        label: t('common.form.fieldGroupName.attribute'),
        value: 'projectExportAttribute',
        columns: arr2,
      };

      BbxExportColumns.value = [fieldsArr, ...(arr2?.length ? [attributeArr] : [])];
    };
    let exportTotalSize = 0;
    const isExportAll = ref(false)

    function filedListParamsFnc(fieldMap, id, tooltip) {
      const { projectExport, projectExportAttribute = [] } = fieldMap;

      return {
        projectSearchForm: { ...searchParams, ...props.params, ...(multipleSelection.value.length && !isExportAll.value ? { id: multipleSelection.value.map(i => i.id) } : {}) },
        totalCount: exportTotalSize,
        fieldList: [...projectExport, ...projectExportAttribute],
        templateId:exportTemplateId.value
      };
    }
    const defaultTabelExportNormalDataHook = useTabelExportNormalDataHook({
      exportFileName: 'ssss',
      pageFnc: () => {
        return { total: exportTotalSize };
      },
      multipleSelectionFnc: ()=>multipleSelection.value,
      BbxExportStorageKey: StorageKeyEnum.PorjectManageListExport,
      exportColumnsFnc: () => BbxExportColumns.value,
      exportHttp: projectListExport,
      filedListParamsFnc,
    });

    async function beforeExport(data1, data2) {
      const listSearchParams = !data1 ? { id: multipleSelection.value.map(i => i.id) } : { ...searchParams, ...props.params };
      let res = await getProjectExportFieldList(listSearchParams);
      if (res?.status !== 0) {
        return Platform.notification({
          title: res.message,
          type: 'error',
        });
      }
      let {
        data: { fieldList, total, templateId },
      } = res;
      if(total === 0 ) {
        return Platform.alert(t('projectManage.projectList.tips1'))
      }
      exportTotalSize = total;
      fieldList = [...fieldList, ...getExportField()]
      setBbxExportColumns(fieldList);
      exportTemplateId.value = templateId
      isExportAll.value = data1
      defaultTabelExportNormalDataHook.BbxExportProduct(data1, data2);
    }

    // 监听列表数据 把选中的匹配出来
    watch(dataList, newValue => {
      matchSelected(newValue);
    });

    onMounted(() => {
      // 获取列表数据
      search(true);
    });

    return {
      defaultTableData,
      loading,
      dataList,
      dataListPageInfo,
      tableContainerHeight,
      searchParams,
      importModalRef,
      importTypeId,

      tableComponentRef,
      multipleSelection,
      handleSelection,
      clearSelection,
      handlerHeaderDragend,
      handlerSortChanged,

      handleSelectColumn,
      openProjectCreateTab,
      openProjectViewTab,
      deleteHandler,
      importHandler,
      handlePageNumChange,
      handleSizeChange,
      search,
      BbxExportColumns,
      beforeExport,
      filedListParamsFnc,
      ...defaultTabelExportNormalDataHook,
      openRichtextVisible,
      baseViewRichTextRef,
      renderDelayedTasks
    };
  },
};
</script>

<style lang="scss" scoped>
.common-list-view__v2 {
  height: 100%;

  .status {
    display: inline-block;
    min-width: 52px;
    max-width: 128px;
    height: 22px;
    line-height: 22px;

    padding: 0 8px;
    font-size: $font-size-small;
    border-radius: 11px;
    color: #fff;

    text-align: center;
    vertical-align: middle;
    @include text-ellipsis();
  }

  ::v-deep .el-progress {
    width: 100%;

    &__text {
      font-size: $font-size-small !important;
    }
  }
}

.import-project {
  position: relative;
  left: -15px;
  padding-left: 15px;

  &:hover &-item {
    display: block;
  }

  &-item {
    position: absolute;
    background: #fff;
    color: $text-color-primary;
    left: -115px;
    top: -8px;
    border: 1px solid #eee;
    border-radius: 4px;
    max-height: 50vh;
    overflow-y: auto;
    display: none;

    > div {
      padding: 4px 15px;
      width: 120px;
      word-break: break-all;

      &:hover {
        background-color: $color-regular;
        color: #77c5c3;
      }
    }
  }
}
</style>
